package com.yl.chainStore.payrule.item.entity

import com.yl.chainStore.common.Constants
import com.yl.chainStore.common.Constants.TableColumn.Companion.TABLE_COLUMN_SELECT_TRANSVERSE_QUERY
import com.yl.chainStore.entity.pay.PayCustomerOrder
import com.yl.chainStore.payrule.common.RuleField
import com.yl.chainStore.payrule.item.ItemRule
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import java.math.BigDecimal
import java.math.RoundingMode

data class BuyAndDiscountRule(

	@RuleField("购买商品","pay/item/getItemSelect",TABLE_COLUMN_SELECT_TRANSVERSE_QUERY)
	var buyItemId:Long,

	@RuleField("购买数量")
	var buyCount:Int,


	var disCountMoney:Long,


): ItemRule {
	override fun validationSelf(): ResponseBody {
		if(buyCount < 0 ){
			return returnError(ErrorCode.DATA_SAVE_FAILED,"购买数量不能小于0")
		}
		if(disCountMoney < 0 ){
			return returnError(ErrorCode.DATA_SAVE_FAILED,"赠送数量不能小于0")
		}

		return returnSuccess()
	}

	override fun canUseForOrder(order: PayCustomerOrder): Boolean {
		for(detail in order.details!!){
			if(detail.gift == 1){
				continue
			}
			if(detail.id == buyItemId){
				return detail.number > buyCount
			}
		}
		return false
	}

	/**
	 * 折扣金额
	 */
	@RuleField(viewName = "折扣金额")
	var disCountMoneyShow: BigDecimal ?= null
		get() {
			if (field == null) {
				return BigDecimal(disCountMoney.div(Constants.OtherConfig.MONEY_TO_DB_DOUBLE)).setScale(2, RoundingMode.HALF_UP)
			}
			return field
		}
		set(value) {
			if (value != null) {
				disCountMoney = (value.multiply(BigDecimal(Constants.OtherConfig.MONEY_TO_DB_DOUBLE))).toLong()
				field = value
			}
		}

}
